//
//  ManagerSelectView.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/21.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift

class ManagerSelectView: UIView {
    
    
    @IBOutlet weak var vwSelectArea: UIView!
    @IBOutlet weak var lblSelectArea: UILabel!
    var arrAreaModel = [ProjectManageModel]()
    var selectAreaId:Variable<String> = Variable("")
    
    @IBOutlet weak var vwSelectCompany: UIView!
    @IBOutlet weak var lblSelectCompany: UILabel!
    var arrCompanyModel = [ProjectManageModel]()
    var selectCompanyId:Variable<String> = Variable("")
    
    @IBOutlet weak var vwSelectManager: UIView!
    @IBOutlet weak var lblSelectManager: UILabel!
    var arrManagerModel = [ProjectManageModel]()
    var selectManagerId:Variable<String> = Variable("")
    var projectModel:ProjectModel!
    
    @IBOutlet weak var btnComfirm: UIButton!
    
    @IBOutlet weak var lblNum: UILabel!
    
    @IBOutlet weak var btnMinus: UIButton!
    
    @IBOutlet weak var btnPlus: UIButton!
    
    
    let disposeBag = DisposeBag()
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        //获取大区数据
        requestAreaData()
        
        //--
        btnMinus.rx.tap.asObservable()
            .subscribe(onNext: { [unowned self] _ in
                var num = Int(self.lblNum.text ?? "") ?? 0
                num -= 1
                if num == 1 {
                    self.btnMinus.isEnabled = false
                    self.btnMinus.alpha = 0.5
                }
                self.lblNum.text = "\(num)"
            }).disposed(by: disposeBag)
        
        //++
        btnPlus.rx.tap.asObservable()
            .subscribe(onNext: { [unowned self] _ in
                var num = Int(self.lblNum.text ?? "") ?? 0
                num += 1
                if num == 2 {
                    self.btnMinus.isEnabled = true
                    self.btnMinus.alpha = 1.0
                }
                self.lblNum.text = "\(num)"
            }).disposed(by: disposeBag)
        
        //选择区域
        let tapArea = UITapGestureRecognizer()
        tapArea.rx.event.asObservable()
            .subscribe(onNext:{ [unowned self] _ in
                if self.arrAreaModel.count == 0 {
                    return
                }
                let pickView = ProjectManagePickView(arrData: self.arrAreaModel, strTitle: "请选择区域", blkConfirm: { [unowned self] (model) in
                    self.clearCompanySelect()
                    self.clearManagerSelect()
                    self.selectAreaId.value = model.id
                    self.lblSelectArea.text = model.name
                    self.requestCompanyData()
                })
                pickView.show(selectId: self.selectAreaId.value)
            }).disposed(by: disposeBag)
        vwSelectArea.addGestureRecognizer(tapArea)
        
        //选择公司
        let tapCompany = UITapGestureRecognizer()
        tapCompany.rx.event.asObservable()
            .subscribe(onNext:{ [unowned self]  _ in
                if self.arrCompanyModel.count == 0 {
                    return
                }
                let pickView = ProjectManagePickView(arrData: self.arrCompanyModel, strTitle: "请选择公司", blkConfirm: { [unowned self] (model) in
                    self.clearManagerSelect()
                    self.selectCompanyId.value = model.id
                    self.lblSelectCompany.text = model.name
                    self.requestManagerData()
                })
                pickView.show(selectId: self.selectCompanyId.value)
            }).disposed(by: disposeBag)
        vwSelectCompany.addGestureRecognizer(tapCompany)
        
        //选择客户经理
        let tapManager = UITapGestureRecognizer()
        tapManager.rx.event.asObservable()
            .subscribe(onNext:{ [unowned self]  _ in
                if self.arrManagerModel.count == 0 {
                    return
                }
                let pickView = ProjectManagePickView(arrData: self.arrManagerModel, strTitle: "请选择区域", blkConfirm: { [unowned self] (model) in
                    self.selectManagerId.value = model.id
                    self.lblSelectManager.text = model.name
                })
                pickView.show(selectId: self.selectManagerId.value)
            }).disposed(by: disposeBag)
        vwSelectManager.addGestureRecognizer(tapManager)
        
        //合并输入流
        let combinInput = Observable.combineLatest(selectAreaId.asObservable(), selectCompanyId.asObservable(), selectManagerId.asObservable()) { return (areaId:$0, companyId:$1, managerId:$2) }.share(replay:1)
        //监控输入流
        combinInput.map { input -> Bool in
            return !input.areaId.isEmpty && !input.companyId.isEmpty && !input.managerId.isEmpty
            }.subscribe(onNext: { [weak self] isValid in
                self?.btnComfirm.isEnabled = isValid
                self?.btnComfirm.alpha = isValid ? 1.0 : 0.5
            }).disposed(by: disposeBag)
        //认购操作
        btnComfirm.rx.tap.asObservable()
            .withLatestFrom(combinInput)
            .flatMapLatest { [unowned self] (input) -> Observable<(Bool,String)> in
                SVProgressHUD.show()
                var goods_type = ""
                for pack in self.projectModel.arrPackage {
                    if pack.isSelect {
                        goods_type = pack.type
                        break
                    }
                }
                return NetworkTool.requestData(url: ActionURL.ORDER_PROJECT, param: [
                        "uid":MainTools.shared.userModel?.uid ?? "",
                        "product_id":self.projectModel.id,
                        "goods_type":goods_type,
                        "region_id":input.areaId,
                        "company_id":input.companyId,
                        "employee_id":input.managerId,
                        "amount":Int(self.lblNum.text ?? "") ?? 0
                        ]).map({ (json) -> (Bool,String) in
                            return (true, json["message"].stringValue)
                        }).catchErrorJustReturn((false,""))
            }.observeOn(MainScheduler.instance)
            .subscribe(onNext:{ result in
                SVProgressHUD.dismiss()
                if result.0 {
                    //认筹成功
                    MainTools.makeToast(message: result.1)
                    self.dismiss()
                    //发送刷新投资页面的通知
                    NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "Flush_Project_List"), object: nil)
                }
            }).disposed(by: disposeBag)
        
    }
    
    var vwContent:UIView?
    //展示
    func show() {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            vwContent = UIView(frame: CGRect(x: 0, y: 0, width: S_Width, height: S_Height))
            vwContent?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
            delegate.window?.addSubview(vwContent!)
            
            vwContent?.addSubview(self)
            self.snp.makeConstraints { (make) in
                make.width.equalTo(313.sp)
                make.height.equalTo(290.sp)
                make.center.equalToSuperview()
            }
        }
    }
    
    //移除
    func dismiss() {
        self.removeFromSuperview()
        vwContent?.removeFromSuperview()
        vwContent = nil
    }
    
    
    @IBAction func cancelAction(_ sender: UIButton) {
        dismiss()
    }
    
    func clearCompanySelect() {
        self.selectCompanyId.value = ""
        self.lblSelectCompany.text = "请选择公司"
        self.arrCompanyModel.removeAll()
    }
    
    func clearManagerSelect() {
        self.selectManagerId.value = ""
        self.lblSelectManager.text = "请选择客户经理"
        self.arrManagerModel.removeAll()
    }
    
    //获取大区数据
    func requestAreaData() {
        SVProgressHUD.show()
        NetworkTool.requestData(url: ActionURL.GET_REGION_DATA, param: ["status":0])
            .map { (json) -> [ProjectManageModel]? in
                return ProjectManageModel.mj_objectArray(withKeyValuesArray: json["rows"].dictionaryValue["data"]?.arrayObject) as? [ProjectManageModel]
            }.catchErrorJustReturn(nil)
            .observeOn(MainScheduler.instance)
            .subscribe(onNext:{ [unowned self] opData in
                SVProgressHUD.dismiss()
                if let arrModel = opData {
                    self.arrAreaModel = arrModel
                }
            }).disposed(by: disposeBag)
    }
    
    //获取公司数据
    func requestCompanyData() {
        SVProgressHUD.show()
        NetworkTool.requestData(url: ActionURL.GET_FEN_COMPANY, param: ["status":0,"region_id":selectAreaId.value])
            .map { (json) -> [ProjectManageModel]? in
                return ProjectManageModel.mj_objectArray(withKeyValuesArray: json["rows"].dictionaryValue["data"]?.arrayObject) as? [ProjectManageModel]
            }.catchErrorJustReturn(nil)
            .observeOn(MainScheduler.instance)
            .subscribe(onNext:{ [unowned self] opData in
                SVProgressHUD.dismiss()
                if let arrModel = opData {
                    self.arrCompanyModel = arrModel
                }
            }).disposed(by: disposeBag)
    }
    
    //获取客户经理数据
    func requestManagerData() {
        SVProgressHUD.show()
        NetworkTool.requestData(url: ActionURL.GET_CUSTOMER_MANAGER, param: ["status":0,"region_id":selectAreaId.value,"company_id":selectCompanyId.value])
            .map { (json) -> [ProjectManageModel]? in
                return ProjectManageModel.mj_objectArray(withKeyValuesArray: json["rows"].dictionaryValue["data"]?.arrayObject) as? [ProjectManageModel]
            }.catchErrorJustReturn(nil)
            .observeOn(MainScheduler.instance)
            .subscribe(onNext:{ [unowned self] opData in
                SVProgressHUD.dismiss()
                if let arrModel = opData {
                    self.arrManagerModel = arrModel
                }
            }).disposed(by: disposeBag)
    }
    
    

}
